package com.rightsidetech.http.controller.agentAdmin.store;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.rightsidetech.commom.base.DelReq;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.config.RedisKeys;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.enums.ModifyName;
import com.rightsidetech.commom.utils.BeanValidator;
import com.rightsidetech.commom.utils.HttpClient;
import com.rightsidetech.commom.utils.RedisUtils;
import com.rightsidetech.commom.utils.StringUtil;
import com.rightsidetech.http.aspect.Auth;
import com.rightsidetech.http.aspect.Log;
import com.rightsidetech.http.aspect.ModifyLog;
import com.rightsidetech.http.aspect.Token;
import com.rightsidetech.http.base.BaseController;
import com.rightsidetech.system.dtos.request.UpdateOpenStatus;
import com.rightsidetech.system.dtos.request.store.AddSysStoreInfoReq;
import com.rightsidetech.system.dtos.request.store.SysStoreInfoReq;
import com.rightsidetech.system.dtos.request.store.UpdateSysStoreInfoReq;
import com.rightsidetech.system.dtos.response.store.StoreSearchResp;
import com.rightsidetech.system.dtos.response.store.SysStoreInfoResp;
import com.rightsidetech.system.entity.store.SysStoreInfo;
import com.rightsidetech.system.service.SysAgentInfoService;
import com.rightsidetech.system.service.SysStoreInfoService;
import com.rightsidetech.trade.service.TdCommodityUserOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shenyu.client.springmvc.annotation.ShenyuSpringMvcClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Package: com.rightsidetech.http.controller.admin.store
 * @ClassName: SysStoreInfoController
 * @Author: yinj
 * @CreateTime: 2021/10/20 15:13
 * @Description: 门店信息相关
 */
@Slf4j
@RestController
@RequestMapping("/agentAdmin/store")
@ShenyuSpringMvcClient(path = "/agentAdmin/store/**")
@Api(tags = "代理商平台-门店信息相关api")
public class StoreInfoController extends BaseController {

    @Value("${storeCodeUrl}")
    private String storeCodeUrl;

    @Resource
    private SysStoreInfoService sysStoreInfoService;
    @Resource
    private SysAgentInfoService sysAgentInfoService;
    @Resource
    private TdCommodityUserOrderService tdCommodityUserOrderService;

    @Resource
    private RedisUtils redisUtils;

    @Value("${restapi.amap.addressUrl}")
    private String addressUrl;
    @Value("${restapi.amap.key}")
    private String amapKey;

    @Log
    @Token
    @Auth(bizType = Auth.AGENT)
    @GetMapping("/page")
    @ApiOperation("门店分页")
    @ApiOperationSupport(ignoreParameters = {"agentInfoId","areaId"})
    public ResponseData<PageInfo<SysStoreInfoResp>> page(SysStoreInfoReq request){
        ConstraintViolation validate = BeanValidator.validate(request);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        Long loginInfoId = Long.parseLong(getAttribute());
        //获取登录账号代理商id
        Long agentInfoId = sysAgentInfoService.findAgentInfoId(loginInfoId);
        if (StringUtils.isEmpty(agentInfoId)){
            return ResponseData.fail(CodeIdEnum.Expired);
        }
        request.setAgentInfoId(agentInfoId);
        return sysStoreInfoService.page(request);

    }


    @Log
    @Token
    @Auth(bizType = Auth.AGENT)
    @PostMapping("/add")
    @ApiOperation("新增")
    @ApiOperationSupport(ignoreParameters = {"storeNumber","codeImage"})
    @ModifyLog(serviceClass = SysStoreInfoService.class,modifyType = ModifyName.SAVE)
    public ResponseData add(@RequestBody AddSysStoreInfoReq request) throws Exception {
        ConstraintViolation validate = BeanValidator.validate(request);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        String maxStoreNo = getMaxStoreNo();
        request.setStoreNumber(maxStoreNo);
        request.setCodeImage(storeCodeUrl + maxStoreNo);
        Long loginInfoId = Long.parseLong(getAttribute());
        //获取登录账号代理商id
        Long agentInfoId = sysAgentInfoService.findAgentInfoId(loginInfoId);
        if (StringUtils.isEmpty(agentInfoId)){
            return ResponseData.fail(CodeIdEnum.Expired);
        }
        request.setSysAgentInfoId(agentInfoId);
        Map map = new HashMap<>();
        map.put("key", amapKey);
        map.put("address", request.getAdress());

        String provice = null;
        String city = null;
        String area = null;

        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(HttpClient.sendGet(addressUrl, map));
        if (!StringUtil.isNullorEmpty(jsonObject) && jsonObject.getString("status").equals("1") && !StringUtil.isNullorEmpty(jsonObject.get("geocodes"))) {
            JSONArray jsonArray = jsonObject.getJSONArray("geocodes");
            JSONObject jsonObject2 = jsonArray.getJSONObject(0);

            if (!StringUtil.isNullorEmpty(jsonObject2.getString("location"))) {
                provice = jsonObject2.getString("province");
                city = jsonObject2.getString("city");
                area = jsonObject2.getString("district");
            } else {
                return ResponseData.fail("地址错误, 请重新输入地址");
            }
        } else {
            return ResponseData.fail("地址错误, 请重新输入地址");
        }
        return sysStoreInfoService.add(request,provice,city,area);

    }

    @Log
    @Token
    @Auth(bizType = Auth.AGENT)
    @PostMapping("/update")
    @ApiOperation("修改")
    @ModifyLog(serviceClass = SysStoreInfoService.class)
    public ResponseData update(@RequestBody UpdateSysStoreInfoReq request){
        ConstraintViolation validate = BeanValidator.validate(request);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        Long loginInfoId = Long.parseLong(getAttribute());
        //获取登录账号代理商id
        Long agentInfoId = sysAgentInfoService.findAgentInfoId(loginInfoId);
        if (StringUtils.isEmpty(agentInfoId)){
            return ResponseData.fail(CodeIdEnum.Expired);
        }
        SysStoreInfo sysStoreInfo = sysStoreInfoService.selectByPrimaryKey(request.getId());

        if (ObjectUtils.isEmpty(sysStoreInfo)) {
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }

        request.setSysAgentInfoId(agentInfoId);
        ResponseData resp = sysStoreInfoService.update(request, sysStoreInfo);
        if(resp.getCodeId() == 1){
            //判断门店名称是否已修改
            if(!sysStoreInfo.getStoreName().equals(request.getStoreName())){
                //修改购物车门店的名称
                tdCommodityUserOrderService.updateStoreNameByStoreId(request.getId(),request.getStoreName());
            }
        }
        return resp;
    }

    @Log
    @Token
    @Auth(bizType = Auth.AGENT)
    @GetMapping("/find_details")
    @ApiOperation("详情")
    public ResponseData<SysStoreInfoResp> findDetails(Long id){
        Long loginInfoId = Long.parseLong(getAttribute());
        //获取登录账号代理商id
        Long agentInfoId = sysAgentInfoService.findAgentInfoId(loginInfoId);
        if (StringUtils.isEmpty(agentInfoId)){
            return ResponseData.fail(CodeIdEnum.Expired);
        }
        return sysStoreInfoService.findDetails(id,agentInfoId);
    }

    @Log
    @Token
    @Auth(bizType = Auth.AGENT)
    @PostMapping("/is_open")
    @ApiOperation("开启/关闭")
    @ModifyLog(serviceClass = SysStoreInfoService.class)
    public ResponseData open(@RequestBody UpdateOpenStatus req){
        Byte status = req.getStatus();
        Long id = req.getId();
        if (StringUtils.isEmpty(status) || StringUtils.isEmpty(id) || (status != 1 && status != -1)) {
            return ResponseData.fail(CodeIdEnum.IllegalParameter);
        }
        Long loginInfoId = Long.parseLong(getAttribute());
        //获取登录账号代理商id
        Long agentInfoId = sysAgentInfoService.findAgentInfoId(loginInfoId);
        if (StringUtils.isEmpty(agentInfoId)){
            return ResponseData.fail(CodeIdEnum.Expired);
        }
        return sysStoreInfoService.open(id,status,agentInfoId);
    }

    @Log
    @Token
    @Auth(bizType = Auth.AGENT)
    @PostMapping("/del")
    @ApiOperation("删除")
    @ModifyLog(serviceClass = SysStoreInfoService.class)
    public ResponseData del(@RequestBody DelReq req){
        Long id = req.getId();
        if (StringUtils.isEmpty(id)) {
            return ResponseData.fail(CodeIdEnum.IllegalParameter);
        }
        Long loginInfoId = Long.parseLong(getAttribute());
        //获取登录账号代理商id
        Long agentInfoId = sysAgentInfoService.findAgentInfoId(loginInfoId);
        if (StringUtils.isEmpty(agentInfoId)){
            return ResponseData.fail(CodeIdEnum.Expired);
        }
        return sysStoreInfoService.del(id,agentInfoId);
    }

    @Log
    @Token
    @GetMapping("/search")
    @ApiOperation("代理商平台-门店下拉框列表")
    public ResponseData<List<StoreSearchResp>> search(String content){
        Long loginInfoId = Long.parseLong(getAttribute());
        //获取登录账号代理商id
        Long agentInfoId = sysAgentInfoService.findAgentInfoId(loginInfoId);
        if (StringUtils.isEmpty(agentInfoId)){
            return ResponseData.fail(CodeIdEnum.Expired);
        }
        return sysStoreInfoService.search(content,agentInfoId,null);

    }


    private synchronized String getMaxStoreNo(){
        Long incr = 1L;
        try {
            incr = redisUtils.getIncr(RedisKeys.YS_STORE_NO);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        if (incr == 1L){
            String maxStoreNo = sysStoreInfoService.getMaxStoreNo();
            if (StringUtil.notNullAndWhitSpace(maxStoreNo)){
                incr = Long.parseLong(maxStoreNo.replace("YSS", "")) + 1;
                redisUtils.setIncr(RedisKeys.YS_STORE_NO, incr);
            }
        }
        String fillBefore = StrUtil.fillBefore(incr.toString(), '0', 8);
        return "YSS" + fillBefore;
    }



}
